package com.hsogoo.collate.configuration;

import com.hsogoo.collate.utils.NamedThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Value("${threadpool.corePoolSize:5}")
    private int corePoolSize;
    @Value("${threadpool.maxPoolSize:10}")
    private int maxPoolSize;
    @Value("${threadpool.queueSize:200}")
    private int queueSize;
    @Value("${threadpool.keepAlive:120}")
    private int keepAlive;
    @Value("${threadpool.threadPoolName:async.dynamic.executor}")
    private String threadPoolName;

    @Bean
    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueSize);
        executor.setKeepAliveSeconds(keepAlive);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadFactory(threadFactory(threadPoolName));
        executor.initialize();
        return executor;
    }

    private ThreadFactory threadFactory(String name) {
        return new NamedThreadFactory(name);
    }
}
